package jk.fox.common.payload.container;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * Rpc实例简单容器
 * @Auther cuichao
 * @Description: DefaultRpcContainer
 * @Date: create in 2020/4/14 11:10
 */
public class DefaultRpcContainer implements RpcContainer {

    /*容器服务实例后缀*/
    private final String CONTAINER_PROVIDER_SUFFIX = "_Service";
    private final String CONTAINER_CONSUMER_SUFFIX = "_Reference";

    private final ConcurrentMap<String,Object> container = new ConcurrentHashMap<>(32);

    @Override
    public Object getService(String key){
        String pk = ServiceKey(key);
        if(pk == null){
            throw new NullPointerException("the provider key is null or ''");
        }

        return container.get(pk);
    }

    @Override
    public void addService(String key, Object provider){
        String pk = ServiceKey(key);
        if(pk == null){
            throw new NullPointerException("the provider key is null or ''");
        }
        container.put(pk,provider);
    }

    @Override
    public Object getReference(String key) {
        String ck = referenceKey(key);
        if(ck == null){
            throw new NullPointerException("the consumer key is null or ''");
        }
        return container.get(ck);
    }

    @Override
    public void addReference(String key, Object consumer) {
        String ck = referenceKey(key);
        if(ck == null){
            throw new NullPointerException("the consumer key is null or ''");
        }
        container.put(ck,consumer);
    }


    private String ServiceKey(String key){
        if(key == null || "".equals(key.trim())){
            return null;
        }
        return key+CONTAINER_PROVIDER_SUFFIX;
    }

    private String referenceKey(String key){
        if(key == null || "".equals(key.trim())){
            return null;
        }
        return key+CONTAINER_CONSUMER_SUFFIX;
    }


    public Map<String,Object> container(){
        return this.container;
    }





}
